<template>
  <div>
    <a-spin :spinning="loading.header">
    <a-page-header
      style="border: 1px solid rgb(235, 237, 240)"
      :title="currentItem.name"
      @back="() => router.back()"
    >
      <a-descriptions title="用户组信息">
        <a-descriptions-item label="用户组标识">{{ currentItem.ssoUserGroupId }}</a-descriptions-item>
        <a-descriptions-item label="用户组名">{{ currentItem.name }}</a-descriptions-item>
        <a-descriptions-item label="备注">{{ currentItem.remark }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ new Date(currentItem.createTime).toLocaleString() }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{ new Date(currentItem.updateTime).toLocaleString() }}</a-descriptions-item>
      </a-descriptions>
    </a-page-header>
    </a-spin>

        <a-card>
          <a-space>
            <a-input
              v-model:value="listQuery.keyword"
              placeholder="关键字搜索"
              allow-clear
              @keyup.enter="handleFilter"
            />
            <a-button type="primary" :icon="h(SearchOutlined)" @click="handleFilter">搜索</a-button>
          </a-space>
        </a-card>
        <a-card class="mt-2">
          <a-button type="primary" class="mb-4" :icon="h(PlusOutlined)" @click="handleAdd">
            添加成员
          </a-button>
          <a-button style="margin-left: 5px" type="primary" :disabled="!hasSelected" :loading="state.loading" @click="removeGroupIds">
            移除用户组
          </a-button>
          <a-table
            bordered
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :data-source="data"
            :pagination="pagination"
            :loading="loading.table"
            :row-key="(row) => row.ssoUserId + ''"
          >
            <template #bodyCell="{ column, record }">

                <template v-if="column.dataIndex === 'avatar'">
                  <div style="display: flex;align-items: center;">
                    <div><a-avatar :size="30" :src="record.avatar" ></a-avatar></div>
                    <div style="margin-left:5px ">{{record.username}}</div>
                  </div>
                </template>

                <template v-if="column.dataIndex === 'ssoOrganization'">
                  <a-tag color="#108ee9" v-if="record.ssoOrganizationName">{{ record.ssoOrganizationName }}</a-tag>
                  <a-tag color="#f50" v-else>组织丢失</a-tag>
                </template>

              <template v-if="column.dataIndex === 'actions'">
                <a-button size="small" type="link" danger @click="handleDelete(record)">移除用户组</a-button>
              </template>
            </template>
          </a-table>
        </a-card>
        <a-drawer
          width="70vw"
          v-model:open="showModal"
          class="custom-class"
          root-class-name="root-class-name"
          :root-style="{ color: 'blue' }"
          style="color: red"
          title="添加成员"
          placement="right"
        >
          <a-card class="mt-2">
            <a-space>
              <a-input
                v-model:value="listQuery2.keyword"
                placeholder="关键字查询"
                allow-clear
                @keyup.enter="handleFilter2"
              />
              <a-button type="primary" :icon="h(SearchOutlined)" @click="handleFilter2">搜索</a-button>
            </a-space>
            <a-space style="margin-left: 5px">
              <a-button type="primary" :disabled="!hasSelected2" :loading="state2.loading" @click="addUserGroup">
                添加
              </a-button>
            </a-space>
            <a-space>

            <a-table
              bordered
              :row-selection="{ selectedRowKeys: state2.selectedRowKeys, onChange: onSelectChange2 }"
              :columns="columns2"
              :data-source="data2"
              :pagination="pagination2"
              :loading="loading.table2"
              :row-key="(row) => row.ssoUserId + ''"
            >
              <template #bodyCell="{ column, record }">

                <template v-if="column.dataIndex === 'avatar'">
                  <div style="display: flex;align-items: center;">
                    <div><a-avatar :size="30" :src="record.avatar" ></a-avatar></div>
                    <div style="margin-left:5px ">{{record.username}}</div>
                  </div>
                </template>

                <template v-if="column.dataIndex === 'ssoOrganization'">
                  <a-tag color="#108ee9" v-if="record.ssoOrganizationName">{{ record.ssoOrganizationName }}</a-tag>
                  <a-tag color="#f50" v-else>组织丢失</a-tag>
                </template>

                <template v-if="column.dataIndex === 'actions'">
                  <a-button size="small" type="link" danger @click="handleDelete(record)">移除用户组</a-button>
                </template>
              </template>
            </a-table>
            </a-space>
          </a-card>
        </a-drawer>

  </div>
</template>

<script setup lang="ts">
import {computed, h, onMounted, reactive, ref} from 'vue';
import SsoUserGroupMappingApi from '@/api/SsoUserGroupMappingApi';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { Rule } from 'ant-design-vue/es/form';

import { TeamOutlined, AppstoreOutlined } from '@ant-design/icons-vue';
import router from "@/router";
import SsoUserGroupApi from "@/api/SsoUserGroupApi";
import {useRoute} from "vue-router";
import {Key} from "node:readline";
import {SsoUserGroup} from "@/types/entity";
const activeName = ref('1')
const currentItem = ref<SsoUserGroup>({})
const loading=reactive({
  header:false,
  table:false,
  table2:false
})


let columns = [
  { title: '用户账号', dataIndex: 'avatar' ,ellipsis: true   ,fixed: 'left',},
  { title: '用户姓名', dataIndex: 'name' ,ellipsis: true},
  { title: '用户昵称', dataIndex: 'nickname'  ,ellipsis: true},
  { title: '用户组织', dataIndex: 'ssoOrganization'  ,ellipsis: true},
  { title: '手机号', dataIndex: 'phone' ,ellipsis: true },
  { title: '邮箱', dataIndex: 'email'  ,ellipsis: true},
  { title: '描述', dataIndex: 'remark'  ,ellipsis: true},
  {
    title: '操作',
    dataIndex: 'actions',
    align: 'center',
  },
];

let columns2 = [
  { title: '用户账号', dataIndex: 'avatar' ,ellipsis: true   ,fixed: 'left',},
  { title: '用户姓名', dataIndex: 'name' ,ellipsis: true},
  { title: '用户昵称', dataIndex: 'nickname'  ,ellipsis: true},
  { title: '用户组织', dataIndex: 'ssoOrganization'  ,ellipsis: true},
  { title: '手机号', dataIndex: 'phone' ,ellipsis: true },
  { title: '邮箱', dataIndex: 'email'  ,ellipsis: true},
  { title: '描述', dataIndex: 'remark'  ,ellipsis: true},
];

let data = ref([]);
let data2 = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (current, pageSize) => {
    pagination.current = current;
    pagination.pageSize = pageSize;
    getList();
  },
});

const pagination2= reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (current, pageSize) => {
    pagination2.current = current;
    pagination2.pageSize = pageSize;
    getList2();
  },
});

const state2 = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
});

const hasSelected2 = computed(() => state2.selectedRowKeys.length > 0);
const onSelectChange2 = (selectedRowKeys: Key[]) => {
  state2.selectedRowKeys = selectedRowKeys;
};


const state = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
});

const hasSelected = computed(() => state.selectedRowKeys.length > 0);
const onSelectChange = (selectedRowKeys: Key[]) => {
  state.selectedRowKeys = selectedRowKeys;
};



const addUserGroup = () => {
  if (state2.selectedRowKeys.length>0){
  SsoUserGroupMappingApi.save({
    ssoUserGroupId:currentItem.value.ssoUserGroupId,
    ssoUserIds:state2.selectedRowKeys
  }).then(res=>{
    handleFilter2()
    handleFilter()
  })
  }
}

const removeGroupIds = () => {
  if (state.selectedRowKeys.length>0){
  SsoUserGroupMappingApi.delete({
    ssoUserGroupId:currentItem.value.ssoUserGroupId,
    ssoUserIds:state.selectedRowKeys
  }).then(res=>{
    handleFilter()
  })
  }
}


onMounted(async () => {
  await getGroupInfo(useRoute().query.ssoUserGroupId as string)
  getList();
});


const listQuery = reactive<any>({});
const listQuery2 = reactive<any>({});


async function getGroupInfo(id:string){
  loading.header=true
 const res = await SsoUserGroupApi.getById(id)
  currentItem.value=res.data[0]
  loading.header=false

}


function getList() {
  loading.table = true;
  listQuery.ssoUserGroupId=currentItem.value.ssoUserGroupId
  SsoUserGroupMappingApi.page({ index: pagination.current, size: pagination.pageSize, ...listQuery})
    .then((res) => {
      data.value = res.data;
      pagination.total = res.total;
    })
    .finally(() => (loading.table = false));
}

function getList2() {
  loading.table2 = true;
  listQuery2.ssoUserGroupId=currentItem.value.ssoUserGroupId
  SsoUserGroupMappingApi.pageUser({ index: pagination2.current, size: pagination2.pageSize, ...listQuery2 })
    .then((res) => {
      data2.value = res.data;
      pagination2.total = res.total;
    })
    .finally(() => (loading.table2= false));
}


function handleFilter() {
  pagination.current = 1;
  getList();
}

function handleFilter2() {
  pagination2.current = 1;
  getList2();
}

const showModal = ref(false);

function handleAdd() {
  showModal.value = true;
  getList2()
}

function handleDelete(row) {
  Modal.confirm({
    title: '提示',
    content: '确定删除这条记录吗',
    onOk() {
      SsoUserGroupMappingApi.delete({
        ssoUserGroupId:currentItem.value.ssoUserGroupId,
        ssoUserIds:[row.ssoUserId]
      }).then(res=>{
        handleFilter()
      })
    },
    onCancel() {},
  });
}
</script>

<style scoped></style>
